﻿using System;

namespace _5E.Utils.TypeHelper.Extension
{
    /// <summary>
    /// 程序说明：类型扩展
    /// 创建作者：ahl
    /// 创建时间：2012-03-29
    /// </summary>
    public static class TypeExtension
    {
        #region Attribute

        /// <summary>
        /// 尝试获取指定的特性
        /// </summary>
        /// <typeparam name="TAttribute">指定特性类型</typeparam>
        /// <param name="type">当前类型</param>
        /// <param name="outAttribute">指定的特性</param>
        /// <param name="inherit">是否查找继承链,默认:false</param>
        /// <returns>是否存在获取指定的特性</returns>
        public static bool TryGetAttribute<TAttribute>(this Type type, out TAttribute outAttribute, bool inherit = false)
            where TAttribute : Attribute
        {
            outAttribute = default(TAttribute);
            TAttribute[] arrAttribute;
            if (type.TryGetAttributes(out arrAttribute, inherit))
            {
                outAttribute = arrAttribute[0];
                return true;
            }
            return false;
        }

        /// <summary>
        /// 尝试获取指定的特性
        /// </summary>
        /// <typeparam name="TAttribute">指定特性类型</typeparam>
        /// <param name="type">当前类型</param>
        /// <param name="outAttribute">指定的特性</param>
        /// <param name="inherit">是否查找继承链,默认:false</param>
        /// <returns>是否存在获取指定的特性</returns>
        public static bool TryGetAttributes<TAttribute>(this Type type, out TAttribute[] outArrAttribute, bool inherit = false)
            where TAttribute : Attribute
        {
            var hasAttribute = false;
            outArrAttribute = new TAttribute[] { };
            var arrAttribute = type.GetCustomAttributes(typeof(TAttribute), inherit);
            if (0 < arrAttribute.Length)
            {
                hasAttribute = true;
                outArrAttribute = Array.ConvertAll(arrAttribute, attr => attr as TAttribute);
            }
            return hasAttribute;
        }

        #endregion
    }
}
